<template>
  <main-content title="商品分类">
    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <el-form-item label="分类名称">
            <el-input v-model="form.categoryName" placeholder="搜索分类名称" @input="handleCategoryName" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="选择状态" clearable @change="handleStatusChange">
              <el-option label="启用" :value="0" />
              <el-option label="停用" :value="1" />
            </el-select>
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button type="primary" @click="query">查询</el-button>

            <el-button type="primary" @click="showAddChildDialog(-1, {})" v-has="['130101']">新增分类</el-button>
          </el-form-item>
        </template>
      </search-bar>
    </template>
    <div class="table-wrapper">
      <el-table :data="tableData" :default-expand-all="expandAll" stripe v-loading="pageInfo.loading" row-key="id">
        <el-table-column prop="categoryName" label="分类名称" min-width="180" />
        <el-table-column prop="number" label="商品数量" min-width="180" />
        <el-table-column prop="updateTime" label="更新时间" min-width="180">
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="120">
          <template #default="scope">
            <el-switch :model-value="!scope.row.status" :loading="false" @click="handleStatus(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.$index, scope.row)" v-has="['130102']">编辑</el-button>
            <el-button type="primary" link @click="showAddChildDialog(scope.$index, scope.row)"
              v-has="['130101']">新增子分类</el-button>
            <el-button type="danger" link @click="handleStatus(scope.$index, scope.row)" v-has="['130104']"
              v-if="!scope.row.status">停用分类</el-button>
            <el-button type="primary" link @click="handleStatus(scope.$index, scope.row)" v-has="['130103']"
              v-else>启用分类</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <edit v-model:show="isShowEdit" :row="currentRow" @confirmed="handleEditConfirmed" />

    <add-child v-model:show="isShowAddChild" :row="currentRow" @confirmed="handleAddChildConfirmed" />
  </main-content>
</template>
<script lang="ts">
export default {
  name: 'ProductCategory'
}
</script>
<script setup lang="ts">
import {
  getCategory,
  getMerchantInsSimpleList,
  onlineCategory,
} from "@/api/product";

import Edit from "./components/Edit.vue";
import AddChild from "./components/AddChild.vue";
import moment from "moment";

const _debounce = (func: any, delay = 800) => {
  let timer: ReturnType<typeof setTimeout>;

  return function (...args: any[]) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args);
    }, delay);
  };
};

const form = reactive({
  status: "",
  categoryName: null,
});

const pageInfo = reactive({
  loading: true,
});

const tableData = ref([]);
const insList = ref([]);
const isShowEdit = ref(false);
const isShowAddChild = ref(false);
const currentRow = ref({});

const _getInsList = async () => {
  const rs: any = await getMerchantInsSimpleList();

  if (rs.code === 200) {
    insList.value = rs.payload;
  }
};
const expandAll=computed(() => {
  if(form.categoryName||form.status){
    return true
  }else{
    return false
  }
})
const query = async () => {
  pageInfo.loading = true;
  const rs: any = await getCategory({
    ...form,
    // current: pageInfo.currentPage,
    // size: pageInfo.showCount,
  });

  if (rs.code === 200) {
    tableData.value = rs.payload;
  }

  pageInfo.loading = false;
};

const reset = async () => {
  form.status = "";
  form.categoryName = null;
  query();
};

const handleEdit = (rowIndex: number, row: any) => {
  currentRow.value = row;
  isShowEdit.value = true;
};

const handleStatus = (rowIndex: number, row: any) => {
  console.log("打开关闭状态");
  ElMessageBox.confirm(
    `是否确定${row.status ? "启用" : "停用"}分类？`,
    "确认提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      row.statusLoading = true;
      const rs: any = await onlineCategory({ id: row.id, name: row.categoryName });
      row.statusLoading = false;

      if (rs.code === 200) {
        query();
      }
    })
    .catch(() => {
      // 用户取消
    });
};

const showAddChildDialog = (rowIndex: number, row: any) => {
  currentRow.value = row;
  isShowAddChild.value = true;
};

const handleAddChildConfirmed = () => {
  query();
};

const handleEditConfirmed = () => {
  query();
};

const formatTime = (time: number) => {
  return moment(time).format("YYYY-MM-DD HH:MM:SS");
};

const handleStatusChange = _debounce(() => {
  // pageInfo.currentPage = 1;
  query();
});

const handleCategoryName = _debounce(() => {
  // pageInfo.currentPage = 1;
  query();
});

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    query();
    _getInsList();
  },
  {
    deep: true
  }
)

onMounted(() => {
  query();
  _getInsList();
});
</script>

<style scoped lang="scss">
.pagination-wrapper {
  margin-top: 20px;
}
</style>
